<template>
  <div class="correspondence">
    <el-form :model="ResetFrom" status-icon ref="ResetFrom">
          <el-row>
            <el-col :span="4">
               <el-form-item label="" prop="number">
                <el-input v-model="ResetFrom.number" placeholder="请输入TQ号">
                  <template slot="prepend">TQ号</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
               <el-form-item label="" prop="userName">
                <el-input v-model="ResetFrom.userName" placeholder="请输入用户名">
                  <template slot="prepend">用户名</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-form-item label="" prop="realName">
                <el-input v-model="ResetFrom.realName" placeholder="请输入真实姓名">
                  <template slot="prepend">真实姓名</template>
                </el-input>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>

    <div class="from-btns">
      <kt-button :label="$t('重置')" perms="true" type="primary" :size="size" @click="reset('ResetFrom')"/>
      <kt-button  :label="$t('查询')" perms="true"  type="primary" @click="search" :size="size"/>
    </div>
    <kt-button :label="$t('新增TQ号')" perms="correspondence:button:add" type="primary" @click="handleAdd" style="float: left;margin-left: 2%;margin-bottom: 1%"
               :size="size"/>

    <StTable class="table-width" :showBatchDelete='false' outcry 
    permsBind="correspondence:button:bind" 
    permsUnbind="correspondence:button:unbind"
    permsDelete="correspondence:button:delete"
    :data="pageResult" :columns="columns" :loading='loading'
    @findPage="findPage" @handleBinduser="handleBinduser" @handleDelete="handleDelete" @handleUntie="handleUntie">
    </StTable>


    <!--新增TQ界面-->
	<el-dialog class="add-pop" :title="operation?'新增TQ号':'编辑'" width="40%" :visible.sync="dialogTq" :close-on-click-modal="false">
		<el-form :model="addTQdataForm" label-width="80px" :rules="dataFormRules" ref="dataForm" :size="size"
			label-position="right">
			<el-row>
        <el-input type="number" v-model="addTQdataForm.number" placeholder="请输入TQ号" style="width:400px;">
          <template slot="prepend">TQ号</template>
        </el-input>
			</el-row>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button :size="size" @click.native="dialogTq = false">{{$t('action.cancel')}}</el-button>
			<el-button :size="size" type="primary" @click="handleSave" :loading="editLoading">{{$t('action.submit')}}</el-button>
		</div>
	</el-dialog>

  <!--绑定用户界面-->
	<el-dialog class="add-pop" :title="operation?'绑定用户':'编辑'" width="40%" :visible.sync="dialogBinduser" :close-on-click-modal="false">
		
    <el-form :model="PostFrom" label-width="80px" ref="PostFrom" :size="size"
			label-position="right">
      <el-row>
        <el-col :span="5" style="margin-top:2%">三级部门</el-col>
        <el-col :span="18">
          <el-select v-model="PostFrom.threeLevelDeptId" filterable @change="DepartmentList_from_change">
                <el-option
                  v-for="item in DepartmentList_options"
                  :key="item.deptName"
                  :label="item.deptName"
                  :value="item.id"
                  >
                </el-option>
            </el-select>
        </el-col>
      </el-row>
      <el-row  style="margin-top:4%">
        <el-col :span="5" style="margin-top:2%">选择用户</el-col>
        <el-col :span="18">
           <el-select v-model="PostFrom.realName" filterable  @change="queryUserList_from_change">
              <el-option
                v-for="item in queryUserList_options"
                :key="item.id"
                :label="item.realName"
                :value="item"
                >
              </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row style="margin-top:4%">
        <el-col :span='5' style="margin-top:2%">用户名</el-col>
        <el-col :span=18>
          <el-input v-model="PostFrom.userName" :disabled="true" auto-complete="off"></el-input>
        </el-col>
      </el-row>
      <el-row style="margin-top:4%">
        <el-col :span='5' style="margin-top:2%">真实姓名</el-col>
        <el-col :span='18'>
          <el-input v-model="PostFrom.realName" :disabled="true" type="text" auto-complete="off"></el-input>
        </el-col>
      </el-row>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button :size="size" @click.native="dialogBinduser = false">{{$t('action.cancel')}}</el-button>
			<el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading">{{$t('action.submit')}}</el-button>
		</div>
	</el-dialog>
  </div>
  
</template>

<script>
import KtButton from "@/views/Core/KtButton";
import StTable from "@/views/Core/StTable";
import api from "@/http/api";
import axios from "axios";
export default {
  name: "Correspondence",
  components: {
    KtButton,
    StTable
  },
  data() {
    return {
      size: "small",
      editLoading:false,
      pageRequest: { pageNum: 1, pageSize: 10 },
      //查询表单提交参数对象
      ResetFrom: {  
        userName: "",
        realName: "",
        region: "",
        number: "",
        date1: "",
        date2: "",
        delivery: false,
        type: [],
        resource: "",
        desc: "",
        threeDepartment: "",
        role: "",
        pageNum: 0,
        pageSize: 0,
      },
      //双向绑定对象
      PostFrom:{    
        id:"",
        userId:"",     
        userName:"",
        roleName:"",
        realName:"",
        threeLevelDeptId:"",
      },

      //三级部门数据对象
      DepartmentList_options: [],
      //选择用户的数据对象
      queryUserList_options: '',
      //获取所有用户
      Allusers:[],
      
      columns: [
        { prop: "number", label: "TQ号", minWidth: 50 },
        { prop: "userName", label: "用户名", minWidth: 80 },
        { prop: "realName", label: "真实姓名", minWidth: 80 }
      ],
      pageResult: {
        content: []
      },

      operation: false, // true:新增, false:编辑
      dialogTq: false, // 新增编辑界面是否显示
      dialogBinduser: false,
      dataFormRules: {
        number: [{ required: true, message: "请输入TQ号", trigger: "blur" }]
      },

      addTQdataForm: {
        number: ""
      },
      loading: false, // 加载标识
      roles: []
    };
  },

  methods: {
    // 显示新增界面
    handleAdd: function() {
      this.dialogTq = true;
      this.operation = true;
    },

    // 加载用户角色信息
    findUserRoles: function() {
      this.$api.role.findAll().then(res => {
        // 加载角色集合
        this.roles = res.data;
      });
    },

    // 重置
    reset(ResetFrom) {
      this.pageRequest.pageNum = 1;
      this.$refs.ResetFrom.resetFields();
      this.findPage(null)
    },

    // 绑定用户
    handleBinduser: function(params) {
      this.dialogBinduser = true;
      this.operation = true;
      this.PostFrom.id=params.row.id;
      this.PostFrom = Object.assign({}, params.row);
      
      for(let i=0; i<this.Allusers.length; i++){
          if(params.row.userId == this.Allusers[i].id){
            this.PostFrom.threeLevelDeptId=this.Allusers[i].threeLevelDeptId;
            this.PostFrom.roleName =  this.Allusers[i].roleName;
            break;
          }
      }
      //存在已绑定的用户再次绑定用户下拉，实现选中
      if(params.row.userId!=null&&params.row.userId!=""){
      this.get_queryUserList_from();
      }else{
        this.queryUserList_options='';
      }
      
    },

    // 提交
    submitForm() {
      this.$refs['PostFrom'].validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            //提交参数
            let postNForm ={
                id:this.PostFrom.id,
                userId:this.PostFrom.userId,    
            }
            let params = JSON.stringify(postNForm);//转json字符串
            this.$api.user.userBind(params).then(res => {
              this.editLoading = false;
              if (res.result == 1) {
                this.findPage(null);
                this.$message({ message: res.msg, type: "success" }); 
                this.dialogBinduser = false;
                this.$refs['PostFrom'].resetFields();
                //清空用户下拉框，下次绑定必须选择三级部门才能选择绑定用户
                this.queryUserList_options='';
              } else {
                this.$message({message:  res.msg, type: "error"});
              }
            });

          });
        }
      });
    },

    // 解绑操作
		handleUntie(params) {
			this.$confirm('确认解绑该用户？', '提示', {
				type: 'warning'
			}).then(() => {
        let tqID = params.tqId;
        this.loading = true
        this.$api.user.relieveUserBind(tqID).then(res => {
            this.editLoading = false;
            if (res.result == 1) {
              this.findPage(null);
              this.$message({ message: "操作成功", type: "success" });
              this.dialogVisible = false;
            } else {
              this.$message({message: "操作失败, " + res.msg,type: "error"});
            }
          });
			}).catch(() => {
			})
		},

    // 菜单树选中
    deptTreeCurrentChangeHandle(data, node) {
      this.dataForm.deptId = data.id;
      this.dataForm.deptName = data.name;
    },
    // 菜单树选中
    handleOptionClick() {},
    // 获取数据
    findPage(data) {
       if (data !== null) {
         this.loading=true
         this.pageRequest = data.pageRequest;
       }
      this.ResetFrom.pageSize = this.pageRequest.pageSize;
      this.ResetFrom.pageNum = this.pageRequest.pageNum;
      this.$api.user
        .getTQList(this.ResetFrom)
        .then(res => {
          if(res.result == 2){
             this.$message({
              message: res.msg,
              type: "error"
            });
          }else{
            let content = {
              content: res.userBindVoList,
              totalSize: res.total
            };
            this.pageResult = content;
          }
          this.loading=false
        })
        .then(data != null ? data.callback : "");
    },
    // 新增TQ号
    handleSave() {
      this.$api.user.saveTq({number:this.addTQdataForm.number}).then(res => {
        if(res.result===1){
          this.dialogTq=false
          this.findPage(null)
        }
      });
    },
    // 删除TQ
    handleDelete(params){
      let tqid=params.row.id
      this.dialogTq=false;
       this.$confirm('确定删除吗, 是否继续?', '提示', {
         type: 'warning'
       }).then(() => {
         this.$api.user.deleteTq(tqid).then(res => {
          this.$message({type: 'success', message: res.msg});
          this.findPage(null);
        });
       }).catch(() => {
         this.$message({
           type: 'info',  
           message: '已取消删除'
         });          
       });
    },
    // 条件查询
    search(){
      // console.log(this.ResetFrom);
      this.loading=true
      this.pageRequest.pageNum = 1;
      this.findPage(null);
    },


    // 获取三级部门下拉框数据
    get_DepartmentList_from() {
      this.$api.user
        .queryDepartmentList({ }) 
        .then(res => {
          this.DepartmentList_options = res.departmentInfoList;
        });
    },

    DepartmentList_from_change(value) {
      this.PostFrom.threeLevelDeptId = value;
      this.PostFrom.realName=''
      this.PostFrom.userName=''
      //根据部门id查询对应的用户信息
      this.$api.user.queryUserList({userType:3,threeLevelDeptId:this.PostFrom.threeLevelDeptId}).then(res =>  {
          this.queryUserList_options = res.userInfoList;
        });
      // this.get_queryUserList_from();
    },

    // 获取用户列表
    get_queryUserList_from() {
      this.$api.user.queryUserList({userType:3,threeLevelDeptId:this.PostFrom.threeLevelDeptId}).then(res =>  {
          this.queryUserList_options = res.userInfoList;
        });
    },

    //获取所有用户
    get_allUsers(){
        this.$api.user.queryUserList({userType:3,threeLevelDeptId:this.PostFrom.threeLevelDeptId}).then(res =>  {
           this.Allusers = res.userInfoList;
        });
    },

    queryUserList_from_change(value) {
      this.PostFrom.userId = value.id;
      this.PostFrom.realName = value.realName;
      this.PostFrom.roleName=value.roleName;
      this.PostFrom.userName= value.userName; 
    },

  },

  mounted() {
    this.get_allUsers();
    this.get_DepartmentList_from();
  }
};
</script>

<style >
@import url("../../assets/queryBox.css");
</style>
<style scope>
.add-btns .el-button:nth-child(1) {
  margin-right: 10px;
}

.el-row .el-col {
  margin-left: 2%;
}

.slect-title-w {
  width: 100px;
}
.add-pop .el-row .el-col{
  margin-left: 0;
}
</style>
